package com.zego.wawaji.ui.start;

import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.zego.wawaji.R;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.toast.PToast;
import com.zego.wawaji.ui.UIShow;
import com.zego.wawaji.ui.bean.LoginResult;
import com.zego.wawaji.ui.dialog.LoadingDialog;
import com.zego.wawaji.ui.dialog.popup.BottomPopup;
import com.zego.wawaji.wawaji_client.AppTinkerLike;

/**
 * 登录测试弹框
 * Created by Su on 2018/2/24.
 */
public class LoginTestDialog extends BottomPopup implements View.OnClickListener, TextWatcher {
    private ImageView btnClear;
    private EditText editCode;

    public LoginTestDialog(FragmentActivity activity) {
        super(activity);
    }

    @Override
    protected View makeContentView() {
        View inflate = LayoutInflater.from(activity).inflate(R.layout.login_test_dialog, null);
        btnClear = (ImageView) inflate.findViewById(R.id.btn_clear);
        btnClear.setOnClickListener(this);
        editCode = (EditText) inflate.findViewById(R.id.edt_code);
        editCode.addTextChangedListener(this);
        inflate.findViewById(R.id.btn_submit).setOnClickListener(v -> {
            String uid = editCode.getText().toString();
            if (TextUtils.isEmpty(uid)) {
                PToast.showShort("请输入登录ID");
                return;
            }
            LoadingDialog.show(activity, "正在登录");
            ModuleMgr.getLoginMgr().reqLoginTest(Long.valueOf(uid), response -> LoadingDialog.closeLoadingDialog(200, () -> {
                PToast.showShort(response.getMsg());
                if (!response.isOk()) {
                    return;
                }

                dismiss();
                LoginResult data = (LoginResult) response.getBaseData();
                ModuleMgr.getLoginMgr().setCookie(data.getAuth());
                ModuleMgr.getLoginMgr().putAllLoginInfo(data.getUid(), true);
                UIShow.showMainClearTask(AppTinkerLike.activity);
            }));

        });

        inflate.findViewById(R.id.btn_close).setOnClickListener(v -> dismiss());
        return inflate;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_clear:
                editCode.setText("");
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int num = s.toString().length();
        btnClear.setVisibility(num > 0 ? View.VISIBLE : View.GONE);
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
}